const mongoose = require('mongoose');
const Album = require('../model/album.model');
var multer=require('multer');
var path=require('path')
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './uploads')
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
    }
  })
var upload = multer({ storage: storage }).single('avatar');

exports.uploadFile=function(req,res,next) {
      upload(req,res,function(err){
          console.log(req.file);
          var uploads = new Album(req.file);
          uploads.save().then(data => {
            res.json(data)
        });
      });

};

//删
exports.remove = function(req,res,next){
    const id = req.params.id;
    console.log(req.params.id)
    Album.findByIdAndRemove(id,function(err,data){
        res.json({message:'删除成功'});
        
    });
}

//改
exports.update = function(req,res,next){
    const id = req.params.id;
    Album.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data => {
        res.json(data);
    });
} 

// exports.uploadFile=function(req,res,next){

// }

//查
// exports.title = function(req,res,next){
//     const title = req.params.title;
//     News.find({title:title},function(err,result){
//         result.rows = result.docs;
//         delete result.docs;
//         res.json(result);
//     })
// }


exports.list = function(req,res,next){
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 10;
    var queryCondition = {};


    if(req.body.title && req.body.title.trim().length>0){
        title = req.body.title;
        queryCondition = {
            title:new RegExp(title,'i')
        }
    }
    
    if(req.body.cateId && req.body.cateId.trim().length>0){
        cateId = req.body.cateId;
        queryCondition = Object.assign(queryCondition,{
            cateId:cateId
        });
    }
    
    Album.paginate(queryCondition,{page:page,limit:limit},function(err,result){
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
}







exports.listpl = function(req,res,next){
    var id = req.params.id;
    Album.find({sid:id}).then(data => {
        res.json(data);
    });
}